package com.wl.api.common.utils;

import java.text.DecimalFormat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class BaseController {

	// protected Logger logger = Logger.getLogger(this.getClass());

	private static final long serialVersionUID = 6357869213649815390L;
	
	
	//public static final String wx_access_token_key = "weixin_access_token"; 
	

	@Autowired
	CacheManager cachemanager;

	/**
	 * 得到ModelAndView
	 */
	public ModelAndView getModelAndView() {
		return new ModelAndView();
	}

	private Cache getUserCache() {
		return cachemanager.getCache("users");
	}

	private Cache getAccessCache() {
		return cachemanager.getCache("access_token");
	}
	
	private Cache getCache(String cachekey) {
		return cachemanager.getCache(cachekey);
	}
	
	public void addCache(String cacheKey, String key , Object value) {
		getCache(cacheKey).put(new Element(key, value));
	}
	
	@SuppressWarnings("unchecked")
	public <T> T getCache(String cacheKey, String key, Class<T> classs) {
		Element ele = getCache(cacheKey).get(key);
		return ele == null ? null: (T) ele.getObjectValue();
	}
	
	@SuppressWarnings("unchecked")
	public Object getCache(String cacheKey, String key) {
		Element ele = getCache(cacheKey).get(key);
		return ele == null ? null:  ele.getObjectValue();
	}
	
	
	public void addAccessCache(String key, Object value) {
		getAccessCache().put(new Element(key, value));
	}
	
	public void addUserCacheElement(String key, Object value) {
		getUserCache().put(new Element(key, value));
	}
	
	@SuppressWarnings("deprecation")
	public Object getUserUserCacheValue(String key) {
		Element ele = getUserCache().get(key);
		return ele == null ? null : ele.getValue();
	}
	
	public Object getAccessCacheValue(String key) {
		Element  el = getAccessCache().get(key);
		return el== null ? null: el.getObjectValue();
	}

	/**
	 * 得到request对象
	 *//*
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		return request;
	}

	public UserDTO getUser(HttpServletRequest req) throws RWYException {
		UserDTO user = (UserDTO) getUserUserCacheValue(req.getParameter(common_token));
		if(ObjectUtil.isEmpty(user)) throw RWYException.create(401);
		return user;
	}

	public EmployeeDTO getEmployee() throws RWYException  {
		String key = getRequest().getParameter(common_token);
		EmployeeDTO user =(EmployeeDTO)getUserUserCacheValue(key);
		
		if(ObjectUtil.isEmpty(user)) throw RWYException.create(401);
		
		return user;
	}*/
	
	public static String dateFormatToString(Object data) {
		DecimalFormat df = new DecimalFormat("0.##");
		return df.format(data);
	}
}
